package cn.edu.zjut.controller;

import cn.edu.zjut.base.BaseController;
import cn.edu.zjut.entity.ImageEntity;
import cn.edu.zjut.entity.UserEntity;
import cn.edu.zjut.service.IImageService;
import cn.edu.zjut.service.IUserService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author:ZhouDan
 * @date: 2020/8/10
 * @version: 1.0
 */
@Slf4j
@RestController
public class ImageController extends BaseController {

    @Autowired
    private IImageService imageService;
    @Autowired
    private IUserService userService;

    private BufferedImage image;
    // 图片的宽度
    private int imageWidth = 2677;
    // 图片的高度
    private int imageHeight = 1890;

    private String path1 = File.separator + "www" + File.separator + "server" + File.separator + "tomcat" + File.separator + "webapps"+ File.separator + "bootcamp" + File.separator;

    @PostMapping("/graphicsGeneration")
    public Object graphicsGeneration(@RequestBody UserEntity userEntity) throws Exception {
        UserEntity user = userService.getByUserNameAndTelephone(userEntity.getUserName(),userEntity.getTelephone());
        if (user == null) {
            return response(1016, null);
        }
        int hTip = 60;
        image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        // 设置图片的背景色
        Graphics2D main = image.createGraphics();
        main.setColor(Color.white);
        main.fillRect(0, 0, imageWidth, imageHeight);

        // ***********************照片**************
        Graphics mainPic = image.getGraphics();
        BufferedImage bimg = null;
        try {
            bimg = javax.imageio.ImageIO.read(new java.io.File(path1 + "images" + File.separator + "0.jpg"));
        } catch (Exception e) {
        }

        if (bimg != null) {
            mainPic.drawImage(bimg, 0, 0, 2677 , 1890, null);
            mainPic.dispose();
        }
        Graphics2D tip = image.createGraphics();
        // 填充区域并确定区域大小位置
        tip.fillRect(0, 2677, 1890, hTip);
        // 设置字体颜色，先设置颜色，再填充内容
        tip.setColor(new Color(24,44,103));
        // 设置字体

        ClassPathResource fontResource = new ClassPathResource("FZXRJWGB10.TTF");

        Font tipFont = Font.createFont(Font.TRUETYPE_FONT, fontResource.getInputStream());
        tipFont = tipFont.deriveFont(Font.BOLD, 120);
        //Font tipFont = new Font("楷体", Font.BOLD , 120);
        tip.setFont(tipFont);
        tip.drawString(user.getUsername(), 380, 725);
        //tip.drawString("何治宇", 380, 725);
        //String path = path1 + "images" +File.separator + user.getUserName() + ".png";
        String path = path1 + "images" +File.separator + user.getUserName() + ".png";
        createImage(path);
        log.info("生成图片成功");
        ImageEntity imageEntity = new ImageEntity();
        imageEntity.setName(user.getUserName());
        if (imageService.getByName(user.getUserName()) != null) {
            return response(200, imageService.getByName(user.getUserName()));
        }
        imageEntity.setTime(3);
        imageEntity.setPath("images" + File.separator + user.getUserName() + ".png");
        imageEntity.setUserId(user.getId());
        imageEntity.setIsDelete(0);
        user.setImageEntity(imageEntity);
        try {
            byte[] imageContent;
            imageContent = fileToByte(new File(path));
            final HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            Map<String,Object> map = new HashMap<>(16);
            map.put("imageEntity",userService.save(user).getImageEntity());
            map.put("imageContent",imageContent);
            return response(200, map.get("imageEntity"));
        } catch (Exception e) {
            return response(1019, e);
        }

    }

    @PostMapping("/download")
    public Object download(@RequestBody UserEntity userEntity, HttpServletResponse response) throws UnsupportedEncodingException {
        UserEntity user = userService.getByUserName(userEntity.getUserName());
        if (user == null) {
            return response(1016, null);
        }
        ImageEntity imageEntity = imageService.getByUserId(user.getId());
        if (imageEntity.getTime() <= 0) {
            return response(1000, imageEntity.getTime());
        }
            imageEntity.setTime(imageEntity.getTime() - 1);

        return response(200, imageService.save(imageEntity));
    }

    @SuppressWarnings("restriction")
    public void createImage(String fileLocation) {
        BufferedOutputStream bos = null;
        if (image != null) {
            try {
                FileOutputStream fos = new FileOutputStream(fileLocation);
                bos = new BufferedOutputStream(fos);

                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
                encoder.encode(image);
                bos.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static byte[] fileToByte(File img) throws Exception {
        byte[] bytes = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            BufferedImage bi;
            bi = ImageIO.read(img);
            ImageIO.write(bi, "png", baos);
            bytes = baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            baos.close();
        }
        return bytes;
    }
}
